from cassacoproject.cassaco.models import Spent
from cassacoproject.cassaco.models import Category
from cassacoproject.cassaco.models import Subcategory
from cassacoproject.cassaco.models import Mode
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
import csv
import datetime
import tempfile

def export(request):
    toDate = request.POST.get('to', None)
    fromDate = request.POST.get('from', None)
    all = request.POST.get('all', None)
    format = request.POST['format']
    
    if format == 'csv': #only supports this for now
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename=export.csv'
        writer = csv.writer(response)
        
        spent = []
        
        if all == 'all': #the user wants to export all spent
            spent = Spent.objects.all()
        elif toDate or fromDate: #the user want only a subset by date range
            spent = Spent.objects.filter(date__gte=fromDate or '1900-01-01', 
                                 date__lte=toDate or datetime.datetime.now())
        
        for s in spent:
            writer.writerow([s.description, s.date, s.category.description, 
                s.subcategory.description, s.mode.description, s.value])
            
        return response
        
def import_(request):
    
    if request.POST['format'] == 'csv':
        file_ = request.FILES['file']
        if file_:
            _importCSV(file_)            
                
        return HttpResponseRedirect(reverse('cassacoproject.cassaco.views.index'))

def _importCSV(file_):
    reader = csv.reader(file_)
            
    for line in reader:
        spent = Spent()
        spent.description = line[0]
        spent.value = line[-1]
        spent.date = line[1]
        spent.category = _decideCategory(line[2])
        spent.subcategory = _decideSubcategory(spent.category, line[3])
        spent.mode = _decideMode(line[4])
        spent.save()
        
def _decideCategory(description):
    """Decide whether to get or create a new Category"""
    cat = None
    try:
        cat = Category.objects.get(description=description)
    except ObjectDoesNotExist, d:
        cat = Category.objects.create(description=description)
        cat.save()
    return cat

def _decideSubcategory(category, description):
    """Decide whether to get or create a new Subcategory"""
    subcat = None
    try:
        subcat = Subcategory.objects.get(description=description,
                                         category=category)
    except ObjectDoesNotExist, d:
        subcat = Subcategory()
        subcat.category = category
        subcat.description = description
        subcat.save()
    return subcat

def _decideMode(description):
    """Decide whether to get or create a new Mode"""
    mode = None
    try:
        mode = Mode.objects.get(description=description)
    except ObjectDoesNotExist, d:
        mode = Mode.objects.create(description=description)
        mode.save()
    return mode


_importCSV(open('/home/yguarata/Desktop/Dinheiro 2008.csv'))